<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/29
 * Time: 14:23
 */

namespace app\api\controller;


use app\common\controller\Base;
use think\Db;
use think\Cache;
use app\common\logic\Pocessing;
use think\Cookie;

header("ACCESS-CONTROL-ALLOW-ORIGIN:http://114.215.68.205");

class CreatLove extends Base
{
    public function _initialize(){

        header("Content-type:text/html;charset=utf-8");
        parent::_initialize();
        $start = array(
            'user_all'                     => $this->user_all,
            'app_down'                 => $this->app_down,
            'logo'                          => $this->logo,
            'now_time_windows' => $this->now_time_windows
        );
        //判断投注功能是否开启
        $zhuh_class_ifopen = Db::name('xt_tzms')->find();
        if($zhuh_class_ifopen['chedan']) {
            $this->chedan = 1;
        } else {
            $this->chedan = 0;
        }
        //判断追号功能是否开启
        if($zhuh_class_ifopen['zhuihao']) {
            $this->zhuihao = 1;
        } else {
            $this->zhuihao = 0;
        }
        $this->lot = new Pocessing();
        $this->assign('cur','shop');
        $this->assign($start);
        $this->assign('chedan',$this->chedan);
        $this->assign('zhuihao',$this->zhuihao);
    }
     /**
     * 72小时候自动删除试玩账号
     */
    public function deleteSwzh(){
    	$time = strtotime(date("Y-m-d",strtotime("-3 day")).' 23:59:59');
    	$name=array();
    	$sw = Db::name('xt_shiwan')->where('id',1)->find();
    	$touzhu = Db::name('touzhu_list_no')->select();
    	foreach ($touzhu as $tz){
    		if(strpos($tz['username'], $sw['qianzhui'])!==false){
    			$name[]= $tz['id'];
    		}
    	}
    	if(Db::name('touzhu_list_no')->where('id','IN',$name)->delete()){
    		echo '成功';
    	}
    	if(Db::name('username')->where('reg_time','<',$time)->where('swzh',1)->delete()){
    		Db::name('touzhu_list_sw')->where('tz_time','<',$time)->delete();
    		echo '删除成功';
    	}
    }
//定时清除投注结果数据
    public function clearTouzhu(){

        $limit =strtotime(date('Y-m-d 23:59:59',strtotime('-2 month')));
        if( Db::name("touzhu_list_ok")->where('tz_time','<',$limit)->delete() ){
            echo '清理投注信息成功'.PHP_EOL;
        }else{
            echo '清理投注信息失败'.PHP_EOL;
        }

    }
    //定时清除开奖结果数据
    public function clearKjjg(){
    
    
    	$low = [51,9,7,5,62,63,72]; //七星彩,港彩⑥合,福彩3D,排列三,分分时时彩,极速PK10,极速快三
    	$limit = strtotime(date('Y-m-d 23:59:59',strtotime('-3 month')));
    	if( Db::name("kjjg_list")->where(['czid'=>['not in',$low],'jztime'=>['<',$limit]])->delete() ){
    		echo '清理A开奖结果成功'.PHP_EOL;
    	}else{
    		echo '清理A开奖结果失败'.PHP_EOL;
    	}
    
    	$limit_b = strtotime(date('Y-m-d 23:59:59',strtotime('-1 month')));
    
    	if( Db::name("kjjg_list")->where(['czid'=>['in',[62,63,72]],'jztime'=>['<',$limit_b]])->delete() ){
    		echo '清理B开奖结果成功'.PHP_EOL;
    	}else{
    		echo '清理B开奖结果失败'.PHP_EOL;
    	}
    
    }
    // 发送邮件
    public function eml_kjno()
    {
    	//$title ='no表有未结算的记录';
    	/*$date = Db::query("SELECT czid from (
    	 SELECT czid,qihao from kkty_touzhu_list_no GROUP BY czid,qihao
    	)as a GROUP BY czid HAVING(COUNT(*)>1) ");
    
    	if($date){
    	foreach($date as $v){
    	$czid =$v['czid'].'、';
    	}
    	$tosend = Db::name('xt_kflink')->where('type', 5)->column('qq');
    	//循环发送
    	foreach($tosend as $v){
    	$destination=$v;
    	$message='有未结算的记录 id '.$czid."请尽快处理";
    	echo  setEmail($title,$message,$destination);
    	}
    	}*/
    
    	$date = Db::query("SELECT czid,qihao,count(*)as n from kkty_touzhu_list_no GROUP BY czid,qihao");
    
    	foreach($date as $v){
    			
    		$czid =$v['czid'];
    		$qihao =$v['qihao'];
    		$n =$v['n'];
    			
    		$date = Db::query("SELECT * from kkty_kjjg_list where czid= $czid and qihao=$qihao and kjjg >0");
    
    		if($date){
    			$tosend = Db::name('xt_kflink')->where('type', 5)->column('qq');
    			$title ='no表有未结算的记录 期号 '.$qihao."  id ".$czid;
    			foreach($tosend as $v){
    				$destination=$v;
    				$message='您好，有未结算的记录， id：'.$czid." 期号是: ".$qihao." 投注记录".$n."  条 ， 请尽快处理。";
    				echo  setEmail($title,$message,$destination);
    			}
    		}
    
    	}
    
    
    }
    /**
     * CM(三胖)
     * 每月发放彩金
     * @return Ambigous <\think\response\Json, \think\Response, \think\response\View, \think\response\Xml, \think\response\Redirect, \think\response\Jsonp, unknown, \think\Response>
     */
    public function cjDayGrant(){
    	if(date('d',time()) == 1){
    		Db::startTrans();
    		try {
    			/**todo remove zdtzxd*/
    			$us_class = Db::name('us_class')->column('id,mearmoney,zxtzxd');
    			$user = Db::name('username')
    			->alias('a')
    			->join('__TOUZHU_LIST_OK__ b','b.username=a.username')
    			->field('a.username,a.us_class,SUM(b.tzje) as tzje')
    			->group('a.username,a.us_class')
    			->where('tz_time','between',timeSelection(3))
    			->select();
    			foreach ($user as $u){
    				/**todo remove  && $us_class[$u['us_class']]['zdtzxd']>=$u['tzje']*/
    				if( $us_class[$u['us_class']]['mearmoney']>0 && $us_class[$u['us_class']]['zxtzxd']<=$u['tzje'] ){
    					$save = Db::name('username')->where('username', $u['username'])->setInc('je', $us_class[$u['us_class']]['mearmoney']);
    					$find_je = Db::name('username')->where('username',$u['username'])->field('je')->find();
    					$data = array();
    					$data['username'] = $u['username'];
    					$data['user_class'] = $u['us_class'];
    					$data['cjje'] = $us_class[$u['us_class']]['mearmoney'];
    					$data['fstime'] = time();
    					$data['beizhu'] = '系统赠送,每月1号定时彩金派送';
    					$data['czadmin'] = '系统赠送';
    					$data['cjhje'] = $find_je['je'];
    					 
    					Db::name('caijin_list')->insert($data);
    				}
    				Db::commit();
    			}
    		} catch (\Exception $e) {
    			 
    			Db::rollback();
    			return json(array('status'=>0,'msg'=>'更新失败'));
    		}
    		return json(array('status'=>1,'msg'=>'更新成功'));
    	}else{
    		return json(array('status'=>0,'msg'=>'参数不对'));
    	}
    }
    
    
    //定时清除线上微信支付宝待支付订单
    public function cleanLineOrderStatus(){
    	$time = strtotime(date('Y-m-d H:i:s', time()) . ' -5 min');
    	$order_sn_arr = Db::name('chongzhi_list')->where(['zt' => 0, 'czclass' => 1, 'from' => 1])->where('cztime', '<', $time)->column('ddbh');
    	if( empty( $order_sn_arr ) ){
    		echo '暂无线上微信,支付宝可清除'.PHP_EOL;
    	}else{
    		$order_sns = join(',', $order_sn_arr);
    		Db::startTrans();
    		try {
    			Db::name('chongzhi_list')->where('ddbh', 'IN', $order_sns)->data(['zt' => 9])->update();
    			Db::name('response_code')->where('remark', 'IN', $order_sns)->update(['status' => 1, 'remark' => '']);
    			$max = Db::name('chongzhi_list')->where('ddbh', 'IN', $order_sns)->field('openren,je,liuyan')->find();
    			$maxje = Db::name('code_account')->where(['type' => $max['liuyan'], 'name' => $max['openren']])->value('max_je');
    			$je = $maxje + $max['je'];
    			Db::name('code_account')->where(['type' => $max['liuyan'], 'name' => $max['openren']])->update(array('max_je' => $je));
    			Db::commit();
    			echo '清除线上微信,支付宝成功'.PHP_EOL;
    		} catch (\Exception $e) {
    			Db::rollback();
    			echo '清除线上微信,支付宝失败'.PHP_EOL;
    		}
    	}
    }
    
    
    //定时清第三方支付订单
    public function cleanThirdOrderStatus(){
    	$time = strtotime(date('Y-m-d H:i:s', time()) . ' -30 min');
    	$order_sn_arr = Db::name('chongzhi_list')->where(['zt' => 0, 'czclass' => 1, 'from' => 0])->where('cztime', '<', $time)->column('ddbh');
    	if( empty( $order_sn_arr ) ){
    		echo '暂无第三方支付订单可清除'.PHP_EOL;
    	}else{
    		$order_sns = join(',', $order_sn_arr);
    		if ( Db::name('chongzhi_list')->where(['ddbh'=>['IN', $order_sns]])->update(['zt' => 9]) ) {
    			echo '清除第三方支付订单成功'.PHP_EOL;
    		} else {
    			echo '清除第三方支付订单失败'.PHP_EOL;
    		}
    	}
    }
    
    
    /**
     * 会员等级晋升
     */
    public function upgrade(){
    	if (strtotime(date('Y-m-d 02:00:00')) <= time() && strtotime(date('Y-m-d 03:00:00')) >= time()) {
    		Db::startTrans();
    		$lv_list = Db::name('us_class')->order('czl asc')->field('id,class_name,dividend,czl,xml')->select();
    		$users = Db::name('username')->where(array('nbzh'=>0,'swzh'=>0))->field('username,je,us_class,czzje,tzzje')->select();
    		foreach($users as $user){
    			$self_class = array_search($user['us_class'], array_column($lv_list, 'id'));
    			$us_lv_list = array_slice($lv_list,$self_class+1);
    			$val = $user['us_class'];
    			foreach ($us_lv_list as $lv){
    				if(floor($user['czzje'])>=floor($lv['czl']) && floor($user['tzzje']) >= floor($lv['xml'])){
    					$val = $lv['id'];
    					$dividend = $lv['dividend'];
    				}else{
    					break;
    				}
    
    			}
    		  
    			if($user['us_class'] != $val){
    				 
    				try {
    					if($dividend > 0){
    						$save = Db::name('username')->where('username', $user['username'])->setInc('je', $dividend);
    
    						$data = array();
    						$zje = $user['je']+$dividend;
    						$data['username'] = $user['username'];
    						$data['user_class'] = $val;
    						$data['cjje'] = $dividend;
    						$data['fstime'] = time();
    						$data['beizhu'] = '系统赠送，会员等级晋升赠送彩金';
    						$data['czadmin'] = '系统赠送';
    						$data['cjhje'] = sprintf("%.2f",$zje);
    						Db::name('caijin_list')->insert($data);
    					}
    					 
    					Db::name('username')->where('username',$user['username'])->setField('us_class',$val);
    					$us = Db::name('username')->alias('u')->join('__US_CLASS__ uc','uc.id=u.us_class')->field('uc.class_name')->where('c.username', $user['username'])->find();
    					$data = array();
    					$data['username'] = $user['username'];
    					$data['test'] = '恭喜您成功晋级为'.$us['class_name'].'。晋级时间为'.date('Y-m-d H:i:s');
    					$data['xx_time'] = time();
    					$data['ifdq'] = 0;
    					Db::name('xiaoxi')->insert($data);
    					Db::commit();
    					echo '晋级成功'.'<br/>';
    				} catch (\Exception $e) {
    					// 回滚事务
    					Db::rollback();
    					echo '参数错误请重试！';
    				}
    		   
    			}else{
    				echo '未达到晋级标准'.$user['username'].'<br/>';
    			}
    		}
    	}else{
    		echo '时间未到晋级时间';
    	}
    	 
    }
    
    //每天 #处代理结算的 5点
    /*public function agentSet()
    {
    	$start = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
    	$end = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
    	$time = [$start, $end];
    	//$touzhu = Db::name('touzhu_list_ok')->where('tz_time', 'between', $time)->select();
    	$touzhu = Db::name('touzhu_list_ok')->where('status',0)->where('tz_time', 'between', $time)->select();
    
    	if (strtotime(date('Y-m-d 04:59:00')) <= time() && strtotime(date('Y-m-d 06:00:00')) >= time()) {
    		foreach ($touzhu as $tz) {
    			$kjjg = Db::name('kjjg_list')->where('czid', $tz['czid'])->where('qihao', $tz['qihao'])->find();
    
    			$status = $this->dailijiesuan($tz['id'],$tz['username'], $tz['tzje'] - $tz['fdje'], $tz['qihao'], $tz['czid']);
    
    			Db::name('touzhu_list_ok')->where('id', $tz['id'])->update(['status' => 1]);
    
    		}
    		echo '代理佣金成功';
    	} else {
    		echo '时间没到';
    	}
    
    }*/
    //代理佣金最新结算
    public function agentJie(){
    	$start = mktime(0, 0, 0, date('m'), date('d') - 3, date('Y'));
    	$end = mktime(0, 0, 0, date('m'), date('d'), date('Y'))-1;
    	$time = [$start, time()];
    
    	$touzhu = Db::name('touzhu_list_ok')->where('status',0)->where('tz_time', 'between', $time)->group('binary username')->column('username');
    	
        $users = Db::name('username')->where(['swzh'=>0,'tjr'=>['<>',' ']])->field('username,0 as num')->select();
        $uu = Db::name('username')->where(['swzh'=>0,'tjr'=>['<>',' ']])->column('username');
    	$yh = array();
    	foreach ($users as $key=>&$us){
    		$name = Db::name('username')->where('username',$us['username'])->value('username');

			if(in_array($name, $touzhu))
			{
				$us['num'] += 1;
			}
    		
    	}
       //print_r($users);
    	if (strtotime(date('Y-m-d 04:59:00')) <= time() && strtotime(date('Y-m-d 06:00:00')) >= time()) {
	    	$touzhus = Db::name('touzhu_list_ok')->where('status',0)->where('tz_time', 'between', $time)->select();
            
	    	foreach ($touzhus as $tz) {
	    		     
	    			$kjjg = Db::name('kjjg_list')->where('czid', $tz['czid'])->where('qihao', $tz['qihao'])->find();
                    if(in_array($tz['username'],$uu)){
    	    			$status = $this->dailijiesuan($tz['tz_time'],$users,$tz['id'],$tz['username'], $tz['tzje'] - $tz['fdje'], $tz['qihao'], $tz['czid']);
    	    
    	    			Db::name('touzhu_list_ok')->where('id', $tz['id'])->update(['status' => 1]);
	               }
	    	}
	    		echo '代理佣金成功';
    	} else { 
    		echo '时间没到';
    	}
    	
    }
    
    
    function dailijiesuan($time,$num,$id,$user, $tzje, $qihao, $czid, $xjrens = 'xjrens>=0', $consumer = '',$i=0)
    {
    	if (!$consumer) {
    		$consumer = $user;
    	}
    	$chaxun = Db::name('username')->where('username', $user)->where($xjrens)->find();
        $m = 0;
    	foreach($num as $cs){
            if($cs['username']==$user){
                $m = $cs['num'];
            }
        }
    	$fan=Db::name('agent_class')->where('num','<=',$m)->where('status',1)->order('num','desc')->find();
        print_r($fan);
    	if($fan){
	    	if ($chaxun['tjr'] != '') {
                echo $user.'---'.$i;
	    		$one_1 = Db::name('username')->where('username', $chaxun['tjr'])->find();
	    		if($i==0){
	    			$dhujd = $tzje / 100 * ($fan['one_yj']);
	    			$fandian = $fan['one_yj'];
	    		}elseif($i==1){
	    			$dhujd = $tzje / 100 * ($fan['two_yj']);
	    			$fandian = $fan['two_yj'];
	    		}else{
	    			$dhujd = $tzje / 100 * ($fan['tree_yj']);
	    			$fandian = $fan['tree_yj'];
	    		}
	    		
	    		if($dhujd>0.01){
	    			$cur_time = time();
	    			$data = [
	    			'agent' => $chaxun['tjr'],
	    			'balance' => $dhujd,
	    			'consumer' => $consumer,
	    			'higher_agent' => $user,
	    			'czid' => $czid,
	    			'qihao' => $qihao,
	    			'true_je' => $tzje,
	    			'add_time' => $cur_time,
	    			'status' => 0,
	    			'ddid' => $id,
	    			'fandian' =>$fandian,
                    'tztime'=>$time
	    			];
	    			Db::name('agent_balance')->data($data)->insert();
	    		}
	    		if ($one_1['tjr'] != '' && $i<3) {
	    			$i++;
	    			$this->dailijiesuan($time,$num,$id,$chaxun['tjr'], $tzje, $qihao, $czid, $xjrens = 'xjrens>0', $consumer,$i);
	    		}
	    
	    	}
    	}
    }
    //还原最大值
    public function MaximumReduction()
    {
    	Db::name('code_account')->where('type', 'alipay')->update(['max_je' => '3000']);
    	Db::name('code_account')->where('type', 'wechat')->update(['max_je' => '2000']);
    	return '好啦';
    }
    //代理定时结算佣金 处理代理佣金的 6点
    
    public function agencySettlement()
    {
    
    	/*$start = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
    
    	$time = [$start, time()];*/
    	/*$open = Db::name('fy_open')->where('id',1)->value('open');
    	if($open==1){*/
        $user = Db::name('username')->where(['swzh'=>0,'fystatus'=>1])->column('username');

    	if (strtotime(date('Y-m-d 05:55:00')) <= time() && strtotime(date('Y-m-d 06:10:00')) >= time()) {
    		$agent = Db::name('agent_balance')
    		//->where('add_time', 'between', $time)
    		->where('status', 0)
            ->where('agent','IN',$user)
    		->field('agent,SUM(balance) as balance,status')
    		->group('agent')
    		->select();
    		$ids = Db::name('agent_balance')
    		//->where('add_time', 'between', $time)
            ->where('agent','IN',$user)    
    		->where('status', 0)
    		->column('id');
    		$je = 0;
    		$data=array();
    		foreach ($agent as $value) {
    			$je = Db::name('username')->where('username', $value['agent'])->value('je');
    			$data = array('balance'=>sprintf("%.2f",$value['balance']),'agent'=>$value['agent'],'fyqje'=>sprintf("%.2f",$je),'add_time'=>time());
    			Db::name('day_agent')->data($data)->insert();
    			Db::name('username')->where('username', $value['agent'])->update(['je' => ['exp',"je+{$value['balance']}"] , 'dlzyj' => ['exp',"dlzyj+{$value['balance']}"]]);
    			//Db::name('username')->where('username', $value['agent'])->update(['je' => $je['je'] + $value['balance'], 'dlzyj' => $je['dlzyj'] + $value['balance']]);
    		}
    
    		foreach ($ids as $id) {
    			Db::name('agent_balance')->where('id', $id)->update(['status' => 1]);
    		}
    		echo '派彩成功';
    	} else {
    		echo '时间没到，不能派彩哦！';
    	}
    	/*}else{
    		echo '未开启自动结算';
    	}*/
    }
    
}